import React from 'react';
import { Provider } from 'react-redux';
import { BrowserRouter, Route, Switch } from 'react-router-dom';
import { routes, RouteType } from './common/routeConfig';
import configStore from './common/configStore';

const store = configStore();

const renderRouteConfig = (routes: RouteType[], contextPath: string) => {
  const children: any = [];

  const renderRoute = (item: any, routeContextPath: string) => {
    let newContextPath: string;
    if (/^\//.test(item.path)) {
      newContextPath = item.path;
    } else {
      newContextPath = `${routeContextPath}/${item.path}`;
    }

    newContextPath = newContextPath.replace(/\/+/g, '/');
    if (item.component && item.childRoutes) {
      const childRoutes = renderRouteConfig(item.childRoutes, newContextPath);
      children.push(
        <Route
          key={newContextPath}
          render={props => <item.component {...props}>{childRoutes}</item.component>}
          path={newContextPath}
        />
      );
    } else if (item.component) {
      children.push(<Route key={newContextPath} component={item.component} path={newContextPath} exact />);
    } else if (item.childRoutes) {
      item.childRoutes.forEach((r: any) => renderRoute(r, newContextPath));
    }
  }
  
  routes.forEach((item: RouteType) => renderRoute(item, contextPath));

  return <Switch>{children}</Switch>
}
 
const App = () => {
  const children = renderRouteConfig(routes, '/');
  return (
    <Provider store={store}>
      <BrowserRouter>
        {children}
      </BrowserRouter>
    </Provider>
  );
}

export default App;
